//
//  DALocalMessageSingletonModel.m
//  DAKnowledge
//
//  Created by DreamArts on 16/7/25.
//  Copyright © 2016年 lidongyang. All rights reserved.
//

#import "DALocalMessageSingletonModel.h"
#import "MJExtension.h"
#import "DADataHandel.h"
#import "DAHeader.h"
#import "Utility.h"

@interface DALocalMessageSingletonModel ()
@property (nonatomic, strong) NSArray *array;
@property (nonatomic, strong) NSMutableArray *moreDataArray;
@property (nonatomic, copy) NSString *userID;
@end

@implementation DALocalMessageSingletonModel

+ (DALocalMessageSingletonModel *)sharedDALocalMessageSingletonModel{
    static DALocalMessageSingletonModel *messageModel = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        messageModel = [[DALocalMessageSingletonModel alloc]init];
    });
    return messageModel;
}
// 数据转换对象
+ (NSMutableArray *)returnModelInArrayWithDic:(NSArray *)array{
    return [DALocalMessageSingletonModel mj_objectArrayWithKeyValuesArray:array];
}
#pragma mark - 网络请求数据
- (void)prepareDataWithUserID:(NSString *)userID lastReplyID:(NSString *)lastID pageNumber:(NSString *)page block:(SingletonModel)block{
    NSString *url = DAMyMessageURL;
    self.userID = userID;
    // 需要用userID 来请求数据
//    NSDictionary *dic = @{@"userID": userID,
//                          @"lastReplyId": lastID};
    NSDictionary *dic = @{@"userID": userID,
                          @"page": page};
    NSLog(@"lastID =%@", lastID);
    NSLog(@"当前页码:%@", page);
    // 开辟线程 异步网络请求数据
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
            if (result && [result[@"result"] isKindOfClass:[NSArray class]]) {
                NSLog(@"网络请求成功");
                if ([result[@"result"] count] > 0) {
                    // 数组里存放 model
                    self.array = [DALocalMessageSingletonModel returnModelInArrayWithDic:result[@"result"]];
                    NSLog(@"%@", [[self.array objectAtIndex:0] replyID]);
                    NSString *lastID = [[self.array objectAtIndex:0] replyID];
                    // 把lastReplyId 存在本地
                    if ([page isEqualToString:@"0"]) {
                        [self archiveLastReplyIDToLocal:lastID];
                       // [self refreshLocalData:result];
                        [self writeDataTolocalWithArray:result];
                    }else{
                       self.moreDataArray = [self loadMoreDataForArray:result[@"result"]];
                    }
                    // 返回block
                    block(YES);
                }else{
                    block(NO);
                }
            }else{
                NSLog(@"网络请求失败");
                block(NO);
                
            }
        }];
    });
}

#pragma mark - 存本地之前 先从本地把数据拿出来
- (void)refreshLocalData:(NSDictionary *)dic{
     NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingString:@"Message"];
    NSMutableDictionary *oldDic = [NSMutableDictionary dictionaryWithContentsOfFile:path];
    if (oldDic == nil) {
        [self writeDataTolocalWithArray:dic];
    }else{
        NSMutableArray *oldArray = oldDic[@"result"];
        NSMutableArray *array = [NSMutableArray array];
        [array addObjectsFromArray:dic[@"result"]];
        [array addObjectsFromArray:oldArray];
        NSLog(@"%@", oldArray);
        oldDic[@"result"] = array;
        NSDictionary *dataDic = oldDic;
        // 在存到本地
        [self writeDataTolocalWithArray:dataDic];
    }
}
#pragma mark - 存本地
- (void)writeDataTolocalWithArray:(NSDictionary *)dic{
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingString:@"Message"];
    NSLog(@"消息  存到本地路径 %@",path);
    BOOL isSuccess = [dic writeToFile:path atomically:YES];
    if (isSuccess) {
        //[[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationUpData" object:nil];
    }
    NSLog(@"数据存入本地:%@", isSuccess?@"成功":@"失败");
}
#pragma mark - 从本地取出数据
- (NSMutableArray *)getLocalDataWithPath:(NSString *)path{
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
   // NSArray *arr = [NSArray arrayWithContentsOfFile:path];
    NSMutableArray *array = [DALocalMessageSingletonModel returnModelInArrayWithDic:dic[@"result"]];
    return array;
}
#pragma mark - 把lastReplyID 存在本地
- (void)archiveLastReplyIDToLocal:(NSString *)lastReplyID{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:lastReplyID forKey:@"lastReplyID"];
}
#pragma mark - 提供一个接口 向外边传递model 数组
- (NSMutableArray *)returnModelArray{
     NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingString:@"Message"];
    NSMutableArray *array = [self getLocalDataWithPath:path];
    return array;
}
#pragma mark - 分页的时候 大于20条不存本地
- (NSMutableArray *)loadMoreDataForArray:(NSArray *)array{
    return [DALocalMessageSingletonModel returnModelInArrayWithDic:array];
}
#pragma mark - 提供接口, 加载更多数据的时候 返回一个数组
- (NSMutableArray *)returnMoreDataArray{
    
    return self.moreDataArray;
}

#pragma mark - 删除本地消息数据
- (void)changeLoacalMessageDataWithIndex:(NSInteger)index withModel:(DALocalMessageSingletonModel *)model{
     NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingString:@"Message"];
    // 先从本地拿到数组
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithContentsOfFile:path];
    NSMutableArray *array = dic[@"result"];
    // 再根据下标进行删除
   // [array removeObjectAtIndex:index];
    // 先遍历
    NSMutableArray *dicArray = [NSMutableArray array];
    for (NSMutableDictionary *dic in array) {
        NSString *replyConten = dic[@"replyContent"];
        NSString *replyDate = dic[@"replyDate"];
        if  ([replyDate isEqualToString:model.replyDate] && [replyConten isEqualToString:model.replyContent]){
           // [array removeObject:dic];
            [self refreshLocalData];
        }else{
            [dicArray addObject:dic];
        }
        
    }
    dic[@"result"] = dicArray;
    
    // 再把删除后的数据 存入本地
    BOOL isChangeSuccessful =[dic writeToFile:path atomically:YES];
    
    if (isChangeSuccessful) {
        NSLog(@"本地数据删除成功");
    }else{
        NSLog(@"删除失败");
    }
    
}

#pragma mark - 刷新本地数据
- (void)refreshLocalData{
    [self prepareDataWithUserID:self.userID lastReplyID:nil pageNumber:@"0" block:^(BOOL isSuccessful) {
        if (isSuccessful) {
            NSLog(@"刷新本地数据成功");
        }
        
    }];
}
@end
